package com.example.user.service.impl;

/**
 * @author FanFu
 * @version 1.0
 * @date 2025/11/8 20:16
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.model.kafka.UserKafkaProducer;
import com.example.user.entity.User;
import com.example.user.mapper.UserMapper;
import com.example.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserKafkaProducer userKafkaProducer;

    private static final String USER_CACHE_PREFIX = "user:";
    private static final String USERNAME_CACHE_PREFIX = "user:username:";

    @Override
    @Transactional
    public boolean save(User user) {
        boolean result = super.save(user);
        if (result && user.getId() != null) {
            // 发送用户注册消息到Kafka
            userKafkaProducer.sendUserRegisterMessage(convertToDto(user));

            // 清除相关缓存
            clearUserCache(user.getId(), user.getUsername());
        }
        return result;
    }
    /**
     * 将实体User转换为DTO User
     * @param user 实体用户对象
     * @return DTO用户对象
     */
    private com.example.common.dto.User convertToDto(User user) {
        if (user == null) {
            return null;
        }

        com.example.common.dto.User dtoUser = new com.example.common.dto.User();
        dtoUser.setId(user.getId());
        dtoUser.setUsername(user.getUsername());
        dtoUser.setEmail(user.getEmail());
        dtoUser.setPassword(user.getPassword());
        dtoUser.setPhone(user.getPhone());
        dtoUser.setStatus(user.getStatus());

        return dtoUser;
    }

    @Override
    @Transactional
    public boolean updateById(User user) {
        User oldUser = this.getById(user.getId());
        boolean result = super.updateById(user);
        if (result) {
            // 发送用户更新消息到Kafka
            userKafkaProducer.sendUserUpdateMessage(convertToDto(user));

            // 清除相关缓存
            clearUserCache(user.getId(), user.getUsername());
        }
        return result;
    }

    @Override
    @Transactional
    public boolean removeById(Long id) {
        User user = this.getById(id);
        boolean result = super.removeById(id);
        if (result && user != null) {
            // 发送用户删除消息到Kafka
            userKafkaProducer.sendUserDeleteMessage(user.getId(), user.getUsername());

            // 清除相关缓存
            clearUserCache(user.getId(), user.getUsername());
        }
        return result;
    }

    @Override
    public User getUserById(Long id) {
        if (id == null) {
            return null;
        }

        String cacheKey = USER_CACHE_PREFIX + id;

        // 先从Redis查询
        User user = (User) redisTemplate.opsForValue().get(cacheKey);
        if (user != null) {
            return user;
        }

        // Redis中没有，查询数据库
        user = this.getById(id);
        if (user != null) {
            // 存入Redis，设置过期时间
            redisTemplate.opsForValue().set(cacheKey, user, 30, TimeUnit.MINUTES);
        }

        return user;
    }

    @Override
    public User getUserByUsername(String username) {
        if (!StringUtils.hasText(username)) {
            return null;
        }

        String cacheKey = USERNAME_CACHE_PREFIX + username;

        // 先从Redis查询
        User user = (User) redisTemplate.opsForValue().get(cacheKey);
        if (user != null) {
            return user;
        }

        // Redis中没有，查询数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        user = this.getOne(queryWrapper);

        if (user != null) {
            // 存入Redis，设置过期时间
            redisTemplate.opsForValue().set(cacheKey, user, 30, TimeUnit.MINUTES);
        }

        return user;
    }

    /**
     * 清除用户相关缓存
     */
    private void clearUserCache(Long userId, String username) {
        // 清除用户ID缓存
        if (userId != null) {
            String userCacheKey = USER_CACHE_PREFIX + userId;
            redisTemplate.delete(userCacheKey);
        }

        // 清除用户名缓存
        if (StringUtils.hasText(username)) {
            String usernameCacheKey = USERNAME_CACHE_PREFIX + username;
            redisTemplate.delete(usernameCacheKey);
        }
    }
}